<script setup>
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import {
  Plus,
  Edit,
  Delete,
  Search,
  RefreshLeft,
} from "@element-plus/icons-vue";
import axios from "axios"; // 引入axios用于API调用

// 部门数据列表
const departments = ref([]);

// 搜索条件
const searchParams = ref({
  name: "",
  status: null,
});

// 部门表单数据
const deptForm = ref({
  id: null,
  name: "",
  status: 1, // 1表示正常
});

// 对话框状态
const dialogVisible = ref(false);
const dialogTitle = ref("添加部门");
const formLoading = ref(false);

// 分页参数
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 筛选后的部门数据
const filteredDepartments = ref([]);

// 加载状态
const loading = ref(false);

// 模拟数据函数，用于调试
function useMockData() {
  filteredDepartments.value = [
    { id: 1, name: "技术部", status: 1, updateTime: "2024-01-01 10:00:00" },
    { id: 2, name: "市场部", status: 1, updateTime: "2024-01-02 11:00:00" },
    { id: 3, name: "财务部", status: 0, updateTime: "2024-01-03 12:00:00" },
    { id: 4, name: "人力资源部", status: 1, updateTime: "2024-01-04 13:00:00" },
    { id: 5, name: "运营部", status: 1, updateTime: "2024-01-05 14:00:00" },
  ];
  pagination.value.total = 5;
}

// 获取部门列表数据
async function fetchDepartmentList() {
  loading.value = true;
  try {
    console.log("发起API请求");
    const response = await axios.get(
      `/api/depts?page=${pagination.value.currentPage}&pageSize=${pagination.value.pageSize}&name=${searchParams.value.name}&status=${searchParams.value.status}`
    );

    console.log("API响应:", response);
    console.log("响应数据:", response.data);

    // 严格按照接口文档处理响应
    if (response.data && response.data.code === 1) {
      // 接口文档中数据在data.rows中
      if (response.data.data && response.data.data.rows) {
        filteredDepartments.value = response.data.data.rows;
        pagination.value.total = response.data.data.total || 0;

        console.log("解析后的数据行:", filteredDepartments.value);
        console.log("解析后的总行数:", pagination.value.total);
      } else {
        filteredDepartments.value = [];
        pagination.value.total = 0;
      }
    } else {
      console.log("API错误:", response.data?.msg || "未知错误");
      ElMessage.error(response.data?.msg || "获取部门列表失败");

      // API返回错误但有响应时，使用模拟数据
      useMockData();
    }
  } catch (error) {
    console.error("获取部门列表异常:", error);
    console.error("错误详情:", error.response || error.message);

    // 错误情况下使用模拟数据，帮助调试
    console.log("使用模拟数据进行调试");
    useMockData();

    ElMessage.warning("使用模拟数据进行展示");
  } finally {
    loading.value = false;
  }
}

// 搜索函数
function handleSearch() {
  pagination.value.currentPage = 1; // 重置到第一页
  fetchDepartmentList();
}

// 清空搜索条件
function handleReset() {
  searchParams.value = {
    name: "",
    status: "",
  };
  pagination.value.currentPage = 1;
  fetchDepartmentList();
}

// 添加部门
function addDepartment() {
  // 重置表单数据
  deptForm.value = {
    id: null,
    name: "",
    status: 1, // 1表示正常
  };
  dialogTitle.value = "添加部门";
  dialogVisible.value = true;
}

// 修改部门
function editDepartment(dept) {
  // 设置表单数据为当前编辑的部门
  deptForm.value = {
    id: dept.id,
    name: dept.name,
    status: dept.status, // 保持原状态值
  };
  dialogTitle.value = "编辑部门";
  dialogVisible.value = true;
}

// 对话框关闭处理
function handleDialogClose() {
  // 可以在这里添加确认提示或其他逻辑
  dialogVisible.value = false;
}

// 提交表单
async function submitForm() {
  // 简单的表单验证
  if (!deptForm.value.name.trim()) {
    ElMessage.warning("请输入部门名称");
    return;
  }

  formLoading.value = true;
  try {
    let response;

    if (deptForm.value.id) {
      // 编辑部门
      response = await axios.put(`/api/depts/${deptForm.value.id}`, {
        name: deptForm.value.name,
        status: deptForm.value.status,
      });
    } else {
      // 添加部门
      response = await axios.post("/api/depts", {
        name: deptForm.value.name,
        status: deptForm.value.status,
      });
    }

    if (response.data.code === 1) {
      ElMessage.success(deptForm.value.id ? "更新成功" : "添加成功");
      dialogVisible.value = false;
      // 重新获取部门列表
      fetchDepartmentList();
    } else {
      ElMessage.error(
        response.data.msg || (deptForm.value.id ? "更新失败" : "添加失败")
      );
    }
  } catch (error) {
    console.error("提交表单异常:", error);
    ElMessage.error("网络异常，请稍后重试");
  } finally {
    formLoading.value = false;
  }
}

// 删除部门
async function deleteDepartment(dept) {
  try {
    // 调用删除部门接口
    const response = await axios.delete(`/api/depts/${dept.id}`);
    if (response.data.code === 1) {
      ElMessage.success("删除成功");
      // 重新获取部门列表
      fetchDepartmentList();
    } else {
      ElMessage.error(response.data.msg || "删除失败");
    }
  } catch (error) {
    console.error("删除部门异常:", error);
    ElMessage.error("网络异常，请稍后重试");
  }
}

// 切换部门状态
async function toggleStatus(dept) {
  try {
    const newStatus = dept.status === 1 ? 0 : 1;
    // 调用更新部门状态接口
    const response = await axios.put(`/api/depts/${dept.id}/status`, {
      status: newStatus,
    });

    if (response.data.code === 1) {
      ElMessage.success("状态更新成功");
      // 重新获取部门列表
      fetchDepartmentList();
    } else {
      ElMessage.error(response.data.msg || "状态更新失败");
    }
  } catch (error) {
    console.error("更新状态异常:", error);
    ElMessage.error("网络异常，请稍后重试");
  }
}

// 分页变化处理
function handleCurrentChange(current) {
  pagination.value.currentPage = current;
  fetchDepartmentList();
}

// 每页条数变化处理
function handleSizeChange(size) {
  pagination.value.pageSize = size;
  pagination.value.currentPage = 1;
  fetchDepartmentList();
}

// 跳转到指定页
function handleJumpToPage(page) {
  const pageNum = parseInt(page);
  if (
    pageNum &&
    pageNum > 0 &&
    pageNum <= Math.ceil(pagination.value.total / pagination.value.pageSize)
  ) {
    pagination.value.currentPage = pageNum;
    fetchDepartmentList();
  }
}

// 组件挂载时先显示模拟数据，同时尝试API调用
onMounted(() => {
  // 立即显示模拟数据，确保页面有内容展示
  useMockData();
  // 然后尝试从API获取真实数据
  fetchDepartmentList();
});
</script>

<template>
  <div class="dept-management">
    <!-- 搜索筛选区域 -->
    <el-card class="search-card">
      <div class="search-form">
        <div class="search-item">
          <el-form-item label="部门名称:" label-width="90px">
            <el-input
              v-model="searchParams.name"
              placeholder="请输入部门名称"
              clearable
              style="width: 200px"
            />
          </el-form-item>
        </div>

        <div class="search-item">
          <el-form-item label="状态:" label-width="60px">
            <el-select
              v-model="searchParams.status"
              placeholder="请选择"
              clearable
              style="width: 150px"
            >
              <el-option label="正常" value="1" />
              <el-option label="停用" value="0" />
            </el-select>
          </el-form-item>
        </div>

        <div class="search-actions">
          <el-button type="primary" @click="handleSearch" :icon="Search"
            >搜索</el-button
          >
          <el-button @click="handleReset" :icon="RefreshLeft">清空</el-button>
        </div>
      </div>
    </el-card>
    <el-card>
      <div class="action-buttons">
        <el-button type="primary" @click="addDepartment" :icon="Plus"
          >添加部门</el-button
        >
      </div>
    </el-card>

    <!-- 部门列表表格 -->
    <el-card class="table-card">
      <el-table
        :data="filteredDepartments"
        style="width: 100%"
        :loading="loading"
        border
        empty-text="暂无数据"
      >
        <el-table-column label="序号" type="index" width="80" align="center">
          <template #default="scope">
            {{
              (pagination.currentPage - 1) * pagination.pageSize +
              scope.$index +
              1
            }}
          </template>
        </el-table-column>

        <el-table-column
          prop="name"
          label="部门名称"
          align="left"
          min-width="150"
        />

        <el-table-column prop="status" label="状态" width="120" align="center">
          <template #default="scope">
            <el-tag
              :type="scope.row.status === 1 ? 'success' : 'danger'"
              size="small"
            >
              {{ scope.row.status === 1 ? "正常" : "停用" }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
          prop="updateTime"
          label="最后修改时间"
          align="center"
          min-width="180"
        />

        <el-table-column label="操作" width="150" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="toggleStatus(scope.row)"
              :text="true"
            >
              {{ scope.row.status === 1 ? "停用" : "启用" }}
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="deleteDepartment(scope.row)"
              :text="true"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <div class="pagination-info">
          共 {{ pagination.total }} 条记录 第 {{ pagination.currentPage }} /
          {{ Math.ceil(pagination.total / pagination.pageSize) }} 页
        </div>

        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="prev, pager, next, jumper, sizes"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          @prev-click="handleCurrentChange"
          @next-click="handleCurrentChange"
        />

        <div class="jump-to">
          跳至
          <el-input-number
            v-model="pagination.currentPage"
            :min="1"
            :max="Math.ceil(pagination.total / pagination.pageSize) || 1"
            @change="handleJumpToPage"
            size="small"
            style="width: 80px; margin: 0 10px"
          />
          页
        </div>
      </div>
    </el-card>

    <!-- 部门添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="400px"
      :close-on-click-modal="false"
      :before-close="handleDialogClose"
    >
      <el-form :model="deptForm" label-width="80px">
        <el-form-item label="部门名称:" prop="name">
          <el-input
            v-model="deptForm.name"
            placeholder="请输入部门名称"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="状态:" prop="status">
          <el-radio-group v-model="deptForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="formLoading">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.dept-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 140px);
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  margin-bottom: 0;
  flex-wrap: nowrap;
  gap: 20px;
}

.search-item {
  display: flex;
  align-items: center;
  margin: 0;
}

.search-actions {
  display: flex;
  gap: 10px;
  margin-left: auto;
}

.action-buttons {
  margin-top: 0;
  margin-left: 20px;
}

.table-card {
  overflow: hidden;
}

.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.pagination-info {
  font-size: 14px;
  color: #606266;
}

.jump-to {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #606266;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }

  .search-item {
    margin-right: 0;
    margin-bottom: 15px;
  }

  .search-actions {
    justify-content: center;
  }

  .pagination-container {
    flex-direction: column;
    gap: 15px;
  }

  .pagination-info {
    order: 3;
  }

  .jump-to {
    order: 2;
  }
}
</style>
